package com.vae.base.utils;

import java.util.Random;

/**
 * 分布式唯一ID生成器的实现，用于生成全局唯一的ID，避免ID重复
 */
public final class IdWorkerUtils {

    // 随机数生成器
    private static final Random RANDOM = new Random();

    // 工作机器id位数
    private static final long WORKER_ID_BITS = 5L;

    // 数据中心id位数
    private static final long DATACENTER_ID_BITS = 5L;

    // 最大工作机器id，即2的WORKER_ID_BITS次方减一
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);

    // 最大数据中心id，即2的DATACENTER_ID_BITS次方减一
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);

    // 序列号位数
    private static final long SEQUENCE_BITS = 12L;

    // 工作机器id左移位数
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;

    // 数据中心id左移位数
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;

    // 时间戳左移位数
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    // 序列号掩码，即2的SEQUENCE_BITS次方减一
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);

    // 单例实例
    private static final IdWorkerUtils ID_WORKER_UTILS = new IdWorkerUtils();

    // 工作机器id
    private long workerId;

    // 数据中心id
    private long datacenterId;

    // 初始时间戳
    private long idepoch;

    // 序列号
    private long sequence = '0';

    // 上次时间戳
    private long lastTimestamp = -1L;

    // 私有构造方法，初始化工作机器id、数据中心id、初始时间戳
    private IdWorkerUtils() {
        this(RANDOM.nextInt((int) MAX_WORKER_ID), RANDOM.nextInt((int) MAX_DATACENTER_ID), 1288834974657L);
    }

    // 私有构造方法，指定工作机器id、数据中心id、初始时间戳
    private IdWorkerUtils(final long workerId, final long datacenterId, final long idepoch) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("工作机器id不能大于%d或小于0", MAX_WORKER_ID));
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("数据中心id不能大于%d或小于0", MAX_DATACENTER_ID));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        this.idepoch = idepoch;
    }

    /**
     * 获取单例实例
     *
     * @return 单例实例
     */
    public static IdWorkerUtils getInstance() {
        return ID_WORKER_UTILS;
    }

    // 同步方法生成下一个id
    public synchronized long nextId() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("时钟倒退，拒绝生成id %d 毫秒", lastTimestamp - timestamp));
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - idepoch) << TIMESTAMP_LEFT_SHIFT)
                | (datacenterId << DATACENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT) | sequence;
    }

    // 等待下一个毫秒
    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    // 获取当前时间戳
    private long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * 生成部件号字符串
     *
     * @return 部件号字符串
     */
    public String buildPartNumber() {
        return String.valueOf(ID_WORKER_UTILS.nextId());
    }

    /**
     * 创建UUID字符串
     *
     * @return UUID字符串
     */
    public String createUUID() {
        return String.valueOf(ID_WORKER_UTILS.nextId());
    }

    // 测试方法
    public static void main(String[] args) {
        System.out.println(IdWorkerUtils.getInstance().nextId());
    }
}